package com.hrg.rds.infra.connect;

import org.apache.plc4x.java.api.PlcConnection;
import org.apache.plc4x.java.api.PlcConnectionManager;
import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public interface ConnectionHolder {
	Logger log = LoggerFactory.getLogger(ConnectionHolder.class);
	PlcConnection getConnection(String connId) throws Exception;
	PlcConnection getConnectionById(String id) throws Exception;

	default PlcConnection getConnection(PlcConnectionManager connectionManager, String connId) throws Exception {
		try (PlcConnection connection = connectionManager.getConnection(connId)) {
			if (!connection.isConnected()) {
				throw new PlcConnectionException("PLC is not connected");
			}
			return connection;
		} catch (PlcConnectionException e){
			log.error("Connection exception in trying to connect", e);
			throw e;
		} catch (CancellationException e){
			log.error("Polling Thread canceled", e);
			throw e;
		} catch (IllegalStateException e){
			log.error("Error in Netty state machine", e);
			throw e;
		} catch (ExecutionException e){
			log.error("Interrupted Exception fired", e);
			throw e;
		} catch (TimeoutException e) {
			log.error("Timeout exception fired", e);
			throw e;
		}
	}
}
